//
var appPath="http://localhost/";
var herosCards;
var pokerCards;
var playerID;

$(document).ready(function(){
  //jQuery UI Button
  //$("button").button();
  //禁用鼠标右键
  $(document).bind("contextmenu",function(){return false;});
  //测试代码
  $("#user1").click(function(){
    if($("#temp_div").size() == 0){
        $("body").append("<div class='temp_div' id='temp_div'><button name='aaa' class='others_card'>黑桃5 【青釭剑】</button><button name='bbb' class='others_card'>黑桃5 【决斗】</button><button name='wugufengdeng' class='others_card'>红桃A 【五谷丰登】</button></div>");
    }
  });
  // 加载所有英雄牌信息。
  $.getJSON(appPath+"src/json/heros.json?t="+new Date(),function(json){
    herosCards = json.standard;
   });
  // 加载所有牌信息。
  $.getJSON(appPath+"src/json/poker.json?t="+new Date(),function(json){
    pokerCards = json.standard;
   });
  playerID=$(".owner").attr("id").substr(4);
});

//======================绑定事件===============================
// 测试代码
$(".others_card").live('click', function() {
  /** 多目标选择TO_DO
  if($(this).attr("name")=="1"){
    $(this).css("background-color","#4169E1");
    $(this).attr("name","2");
  }else{
    $(this).css("background-color","");
    $(this).attr("name","1");
  }
  */
  
//  alert($("#owner_name").html()+"对("+$(this).html()+")使用了"+$("#used_card").val());
  writeGameLog($("#owner_name").html()+"对("+$(this).html()+")使用了"+$("#used_card").val());
  $("#temp_div").remove();
});
// 选英雄牌
$(".hero").live('click', function() {
  // 添加选手ID
  var temp = "{\"userid\":\""+$(".owner").attr("id").substr(4)+"\",";
  $(this).attr("text",temp+$(this).attr("text").substr(1));
  var obj = eval('(' + $(this).attr("text") + ')');
  $.post(appPath+"writeSelectedHeroIntoStatus.php",obj,function(result){
      alert(result);
    });
  $("#temp_div").remove();
});
// 对对方使用牌
$(".card").live('click', function() {
    $("body").append("<div class='temp_div' id='temp_div'><button name='1' class='others_card'>"+$("#"+$("#user_id_1").val()+">#name").html()+"</button><button name='bbb' class='others_card'>"+$("#"+$("#user_id_2").val()+">#name").html()+"</button><button name='wugufengdeng' class='others_card'>"+$("#"+$("#user_id_3").val()+">#name").html()+"</button><button name='wugufengdeng' class='others_card'>"+$("#"+$("#user_id_4").val()+">#name").html()+"</button><button name='wugufengdeng' class='others_card'>"+$("#"+$("#user_id_5").val()+">#name").html()+"</button><hr/><button name='wugufengdeng' class='others_card'>自己</button><button name='wugufengdeng' class='others_card'>所有人</button><button name='wugufengdeng' class='others_card'>装备</button><hr/><button name='wugufengdeng' class='others_card'>弃牌</button><hr/><button name='wugufengdeng' class='others_card'>确定</button><button name='wugufengdeng' class='others_card'>取消</button></div>");
    $("#used_card").val($(this).html());
    $(this).remove();
});

// 禁止文本框使用回车换行和粘贴
$("#chatWindows").live("keydown",function(e){
    if(e.which==13 || e.ctrlKey){
        return false;
    }
});

// 聊天触发事件
$("#chatWindows").live("keyup",function(e){
    if(e.ctrlKey && e.which==13){
        chat();
        $("#chatWindows").val("");
    }
});

//======================函数===============================
// 改变button样式
function changeButtonStyle(target){
  alert(target);
}



// 测试代码.getJSON
function clock() {
  var t=new Date();
  $("#charWindows").val(t);
  $.getJSON("poker.json",function(json){
    alert(json.standard.length);
  });
}
// 读聊天记录
function readChatLog(){
  $.getJSON(appPath+"src/json/chatLog.json?t="+new Date(),function(json){
    var i=0;
    if(json.log.length > 0 && json.log.length > $("#chatBox_msgList > dl").size() ) {
      for(j=$("#chatBox_msgList > dl").size();j<json.log.length;j++){
        $("#chatBox_msgList").append("<dl class='chatBox_myMsg'>"+json.log[j].name + "：" + json.log[j].text +"</dl>");
      }
      $("#chatBox_msgList").scrollTop($("#chatBox_msgList > dl").size()*22);
    }
  });
}

//写聊天纪录
function chat() {
//  t = new Date();
//  var text=t.toLocaleString();
  var text=$("#chatWindows").val();//+"("+t.getHours()+":"+t.getMinutes()+":"+t.getSeconds()+")";
  var name=$("#userName").html();
  $.post("writeChatLog.php",{user:name,message:text});
}

//读游戏记录
function readGameLog(){
$.getJSON(appPath+"src/json/gameLog.json?t="+new Date(),function(json){
 var i=0;
 if(json.log.length > 0 && json.log.length > $("#gameLog > dl").size() ) {
   for(j=$("#gameLog > dl").size();j<json.log.length;j++){
     $("#gameLog").append("<dl class='chatBox_myMsg'>"+json.log[j].text +"</dl>");
   }
   $("#gameLog").scrollTop($("#gameLog > dl").size()*22);
 }
});
}
//写游戏纪录
function writeGameLog(text) {
  $.post("writeGameLog.php",{message:text});
}

//取装备区的牌信息，组合成装备区牌
function getEquipCardDetail(card) {
  if(card==""){
    return ""
  }
  return card.name + "[" + card.symbol + card.number + "]";
}

//取状态区的牌信息。
function getStatusCardDetail(cards,i) {
  if(cards.length<i){
    return "-";
  }else{
    return getCardJSON(cards[i-1]).name.substr(0,1);
  }
}

//取技能信息。
function getSkill(cards,i) {
  if(cards.length<i){
    return "-";
  }else{
    return cards[i-1].name;
  }
}


// 设置主用户手牌
function setOwnerCard(cards) {
  if(cards.length < 1 ){
    //
  }else{
    for(var i=0;i<cards.length;i++){
      card = getCardJSON(cards[i]);
      var cardText = card.name+"["+card.symbol+card.number+"]";
      $("#owner_card").append("<button class='card' id='"+card.id+"'>"+cardText+"</button>")
    }
  }
}
// 取武将牌JSON对象
function getHeroCardJSON(heroCardID){
  for(i=0;i<herosCards.length;i++){
    if(heroCardID == herosCards[i].id){
      return herosCards[i];
    }
  }
  return "";
}

//取普通牌JSON对象
function getCardJSON(cardID){
  if(cardID == ""){
    return "";
  } else {
    for(i=0;i<pokerCards.length;i++){
      if(cardID == pokerCards[i].id){
        return pokerCards[i];
      }
    }
    return "";
  }
}
// 设置用户信息（牌，状态等）
function setPlayerInfo() {
  $(".card").remove();
  $.getJSON(appPath+"src/json/gameStatus.json?t="+new Date(),function(json){
    var playerInfo = json.playerInfo;
    for(var i=0;i<playerInfo.length;i++){
      var j = i+1;
      if(playerID == j){
        setOwnerInfo(playerInfo[i]);
      }else{
        var heroCard = getHeroCardJSON(playerInfo[i].heroCard);
        $("#user"+j+" > #force").html(heroCard.force);
        $("#user"+j+" > #name").html(heroCard.name);
        $("#user"+j+" > #card_count").html(playerInfo[i].cards.length);
        $("#user"+j+" > #blood").html(playerInfo[i].bloodNow);
        $("#user"+j+" > #weapon").html(getEquipCardDetail(getCardJSON(playerInfo[i].weapon)));
        $("#user"+j+" > #armor").html(getEquipCardDetail(playerInfo[i].armor));
        $("#user"+j+" > #defensive_horse").html(getEquipCardDetail(playerInfo[i].defensiveHorse));
        $("#user"+j+" > #offensive_horse").html(getEquipCardDetail(playerInfo[i].offensiveHorse));
        $("#user"+j+" > #status1").html(getStatusCardDetail(playerInfo[i].playerStatus,1));
        $("#user"+j+" > #status2").html(getStatusCardDetail(playerInfo[i].playerStatus,2));
        $("#user"+j+" > #status3").html(getStatusCardDetail(playerInfo[i].playerStatus,3));
        $("#user"+j+" > #status4").html(getStatusCardDetail(playerInfo[i].playerStatus,4));
      }
    }
  });
}

// 设置当前用户信息
function setOwnerInfo(ownerInfo){
  var heroCard = getHeroCardJSON(ownerInfo.heroCard);
  $("#owner_force").html(heroCard.force);
  $("#owner_name").html(heroCard.name);
  $("#owner_bloodNow").html(ownerInfo.bloodNow);
  $("#owner_weapon").html(getEquipCardDetail(getCardJSON(ownerInfo.weapon)));
  $("#owner_armor").html(getEquipCardDetail(getCardJSON(ownerInfo.armor)));
  $("#owner_offensive_horse").html(getEquipCardDetail(getCardJSON(ownerInfo.defensiveHorse)));
  $("#owner_defensive_horse").html(getEquipCardDetail(getCardJSON(ownerInfo.offensiveHorse)));
  setOwnerCard(ownerInfo.cards);
  // 取状态区的牌信息。
  $("#owner_status1").html(getStatusCardDetail(ownerInfo.playerStatus,1));
  $("#owner_status2").html(getStatusCardDetail(ownerInfo.playerStatus,2));
  $("#owner_status3").html(getStatusCardDetail(ownerInfo.playerStatus,3));
  $("#owner_status4").html(getStatusCardDetail(ownerInfo.playerStatus,4));
  // 设置技能
  $("#owner_skill_1").html(getSkill(heroCard.skills,1));
  $("#owner_skill_2").html(getSkill(heroCard.skills,2));
}

//============================================================================
//测试用
function test(){
  var hero;
  $.getJSON("../../status.json?t="+new Date(),function(json){
    hero=json.hero;
    $("body").append("<div class='temp_div' id='temp_div'><button id='hero_card1' name='1' class='hero' text='"+JSON.stringify(hero[0])+"'>"+hero[0].name+"</button><button name='1' class='hero'>"+hero[1].name+"</button><button name='1' class='hero'>"+hero[2].name+"</button></div>");
   });
  
  
}
function test2(){
  $("#owner_weapon").html("武器");
}
function test3(){
  $.get("chatLog.log", function(data){
      alert(data);
  });
  $("#owner_weapon").append("<button class='equip_text'>武器</button>");
}
function test4(){
  alert(playerID);
}

function getPlayerID(){
  return $(".owner").attr("id").substr(4);
}

function getHeroCard(id){
//  alert(herosCards[id].name)
  return herosCards[id];
}

// 选英雄
function selectHeros(){
  $.getJSON(appPath+"src/temp/new_heros.json?t="+new Date(),function(json){
    var i = (getPlayerID()-1)*3;
    var heros=new Array()
    heros[0] = getHeroCard(json[i]);
    heros[1] = getHeroCard(json[i+1]);
    heros[2] = getHeroCard(json[i+2]);
    
    if($(".temp_div").size() == 0){
    $("body").append("<div class='temp_div' id='temp_div'><button id='hero_card1' name='1' class='hero' text='"+JSON.stringify(heros[0])+"'>"+heros[0].name+"</button><button name='1' class='hero' text='"+JSON.stringify(heros[1])+"'>"+heros[1].name+"</button><button name='1' class='hero' text='"+JSON.stringify(heros[2])+"'>"+heros[2].name+"</button></div>");
  }
   });
}


function playCard(){
  
}

// 摸牌
function drawCard(i){
  temp="{\"playerID\":\""+playerID+"\",\"i\":\""+i+"\"}";
  var obj = eval('(' + $(this).attr("temp") + ')');
  $.post(appPath+"drawCard.php",obj,function(result){
    setPlayerInfo();
  });
}
//============================================================================
//                                    执行代码
//============================================================================
function runGame(){
  $.getJSON(appPath+"src/json/gameStatus.json?t="+new Date(),function(json){
    // Phase:1 选英雄
    if(json.gamePhase == 1 && json.playerInfo[playerID-1].phase == "N"){
      selectHeros();
    }else if(json.gamePhase == 2){
//      setPlayerInfo();
    }
   });
}
//自动运行
//var int=self.setInterval("readChatLog()",2000)
self.setInterval("runGame()",2000)





